import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";
interface UserState {
  isLogin: boolean;
  loading: boolean;
  userInfo: {
    username: string;
    nickname: string;
    avator: string;
  };
}

export const login = createAsyncThunk(
  "userSlice/login",
  async (params: { username: string; password: string }, thunkAPI) => {
    const resp = await axios.post("/api/login", params);
    return resp.data;
  }
);

const initialState: UserState = {
  isLogin: false,
  loading: false,
  userInfo: {
    username: "",
    nickname: "",
    avator: "",
  },
};

const userSlice = createSlice({
  name: "userSlice",
  initialState,
  reducers: {},
  extraReducers: {
    [login.pending.type](state) {
      state.loading = true;
    },
    [login.rejected.type](state, action) {
      console.log(action)
      state.loading = false;
      state.isLogin = false;
      state.userInfo = {
        username: "",
        nickname: "",
        avator: "",
      };
    },
    [login.fulfilled.type](state, action) {
      state.loading = false;
      state.isLogin = true;
      state.userInfo = action.payload.data;
    },
  },
});

export const {} = userSlice.actions;
export default userSlice;
